let urlPrefix = "http://localhost:8089/"
import Notify from '@vant/weapp/notify/notify';

App({
  onLaunch() {
    let userinfo = wx.getStorageSync('userinfo');
    if (userinfo != null && Object.keys(userinfo).length > 0) {
      this.globalData.userinfo = userinfo;
    }
  },
  globalData: {
    userInfo: null
  },
  request(path, method, payload, header) {
    return new Promise((resolve, reject) => {
      let url = urlPrefix + path;
      let headers = {};
      let value = "";
      if (header == 'xform') {
        value = 'application/x-www-form-urlencoded'
      } else if (header == 'json') {
        value = "application/json"
      }
      if (value) {
        headers['content-type'] = value;
      }

      let userinfo = wx.getStorageSync('userinfo');
      let tokenName = userinfo.tokenName;
      let tokenValue = userinfo.tokenValue;
      if (tokenName != undefined && tokenName != '') {
        headers[tokenName] = tokenValue;
      }
      let curUrl = this.getCurrentPageUrl();
      wx.request({
        url: url,
        method: method,
        data: payload,
        header: headers,
        success(res) {
          let data = res.data;
          if (data.code == 200) {
            resolve(data)
          } else if (data.code == 401) {
            wx.removeStorageSync('userinfo');
            Notify({
              type: 'danger',
              message: '请先登录',
              selector: '#notify_selector'
            })
            setTimeout(function () {
              wx.setStorageSync('currentPath', curUrl);
              wx.navigateTo({
                url: '/subPackage/view/user/login/index',
              })
            }, 2000);
          } else {
            reject(data);
          }
        },
        reject(e) {
          reject(e);
        }
      })
    })
  },
  getCurrentPageUrl() {
    let pages = getCurrentPages();
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route
    let options = currentPage.options;
    let params = "";
    for (let key in options) {
      let value = options[key];
      if (params) {
        params = key + "=" + value;
      } else {
        params = params + "&" + key + "=" + value;
      }
    }
    if (params) {
      url = url + "?" + params;
    }
    return url;
  }
})
